//
//  HTCompostController.swift
//  weibo
//
//  Created by JonsonLiu on 16/4/26.
//  Copyright © 2016年 liujonson. All rights reserved.
//

import UIKit
import SVProgressHUD
class HTCompostController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        setupTextView()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        self.view.becomeFirstResponder()
    }
/// 设置导航控制器
    private func setupNV(){
        
        view.backgroundColor = UIColor.whiteColor()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "<返回", style: UIBarButtonItemStyle.Plain, target: self, action: "back")
        
        
        navigationItem.titleView = titleView
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    /// 设置textview
    private func setupTextView(){
        
        view.backgroundColor = UIColor.blueColor()
        
        setupNV()
        
        view.addSubview(textView)
        view.addSubview(pictureView)
        if #available(iOS 9.0, *) {
            view.addSubview(composeBar)
        } else {
            // Fallback on earlier versions
        }
        
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        
        if #available(iOS 9.0, *) {
            composeBar.snp_makeConstraints { (make) -> Void in
                make.leading.trailing.equalTo(self.view)
                make.height.equalTo(44)
                make.bottom.equalTo(self.view).offset(-40)
            }
        } else {
            // Fallback on earlier versions
            print("版本不是9.0")
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(10)
            make.top.equalTo(100)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(pictureView.snp_width)
        }
        
        
      NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChageFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
      NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtonClick:", name: "HTEmoticonButtonClickNotification", object: nil)
        
         NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonDeleteButtonClick", name: "HTEmoticonButtonClickNotification", object: nil)
    }
    
    
    @objc private func emoticonDeleteButtonClick(){
        
        textView.deleteBackward()
    }
    
    @objc private func emoticonButtonClick(noti : NSNotification)
    {
        let emotcion = noti.userInfo!["emoticon"] as! HTEmoticon
        
        if emotcion.type == "1"{
        
            textView.insertText((emotcion.code! as NSString).emoji())
        }else{
        
            print("图片表情点击")
        }
    }
    
    /// 微博发送按钮
    ///
    /// - parameter noti: <#noti description#>
    @objc private func send(){
        
        if pictureView.hidden{
            update()
            
        }else{
            upload()
        }
    }
    
    
    private func update(){
    
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        let params = [
            
            "access_token":  HTViewModel.sharedViewModel.accessToken ?? "",
            "status": textView.text!
        ]
        
        NetworkTools.sharedTools.request(.Post, urlString: urlString, parameters: params) { (responseObject, error) -> () in
            
            if error != nil{
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败")
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }

    }
    
    
    private func upload(){
    
        let utlString  = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        let params = [
        
            "access_token": HTViewModel.sharedViewModel.accessToken ?? "",
            "status": textView.text!,
        ]
        
        NetworkTools.sharedTools.POST(utlString, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
            
            let data = UIImagePNGRepresentation(self.pictureView.imagess.first!)!
            
            formData.appendPartWithFileData(data, name: "pic", fileName: "1111", mimeType: "application/octet-stream")
            
            }, progress:nil, success: { (_, response) -> Void in
                
                SVProgressHUD.showSuccessWithStatus("发送成功")
            }) { (_, error) -> Void in
                
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败")
        }
        
    }
    
    
    @objc private func keyboardChageFrame(noti : NSNotification){
    
        let endFram = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        print(endFram)
        
        //调整tabbar位置
        composeBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(endFram.origin.y - UIScreen.mainScreen().bounds.height)
            
        }
    
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    
    @objc private func back(){
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    private lazy var textView : HTTextView = {
    
        let  textView = HTTextView()
        
        textView.delegate = self
        textView.placeholder = "这个夏天不是很冷,也不是很寂寞"
        textView.font = UIFont.systemFontOfSize(11)
        //拖动的时候消失
        textView.keyboardDismissMode = .OnDrag
        //开启垂直弹簧效果
        textView.alwaysBounceVertical = true
        return textView
    }()
    
    @available(iOS 9.0, *)
    private lazy var composeBar : HTComposeToolBar = {
    
        let  composeBar = HTComposeToolBar(frame: CGRectZero)
        
        composeBar.buttonClickClosed = { [weak self](type: HTComposeToolBarType) in
        
        print(type)
            
            switch type{
            
            case .picture:
                self?.selectPicture()
                break
            case .Mention:
                break
            case .Emoticon:
                self?.switchKeyBoard()
                break
            default:
                break
            }
            
        }
        
        return composeBar
    }()
    
    //切换键盘
    private func switchKeyBoard(){
    
        
        textView.inputView = textView.inputView == nil ? emoticonKeyBoard : nil
        
        composeBar.isSystemKeyBoard = textView.inputView == nil
        
        textView.reloadInputViews()
        
        if !textView.isFirstResponder(){
        
            textView.becomeFirstResponder()
        }
    }
    
    
    
    /// MARK : 键盘frame的改变方法
    ///
    /// - parameter noti: <#noti description#>
    
    @objc private func keyBoardChangFrame(noti:NSNotification){
    
        let endFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        print(endFrame)
        
/// 调整 toolbar的位置
        composeBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(endFrame.origin.y - UIScreen.mainScreen().bounds.height)
        }
        
        //执行动画
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    private func selectPicture(){
    
        
        let vc = UIImagePickerController()
        vc.delegate = self
        
        self.presentViewController(vc, animated: true, completion: nil)
    }
    
    
    
    private func text() {
        
    }
    
    /// MARK懒加载一个表情
    private lazy var emoticonKeyBoard : HTKeyBoardView = {
        
        let keyBoard = HTKeyBoardView()
        keyBoard.frame.size = CGSize(width: UIScreen.mainScreen().bounds.width, height: 216)
        return keyBoard
    
    }()
    
 /// 懒加载一个视图
    private lazy var pictureView : HTComposePictrueView = {
       let v = HTComposePictrueView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        
        
        v.selectedPictrueClose = {[weak self] in
            self?.selectPicture()
        }

        return v
    }()
    private lazy var titleView : UILabel = {
    
        let  titleView = UILabel()
        titleView.textColor = UIColor.redColor()
        titleView.font = UIFont.systemFontOfSize(14)
        titleView.numberOfLines = 0
        titleView.textAlignment = .Center
        
        //拖动的时候键盘消失
        
        if let  name = HTViewModel.sharedViewModel.account?.name{
            
            let  text  = "weibo\n\(name)"
            let  range = (text as NSString).rangeOfString(name)
            let  attr = NSMutableAttributedString(string: text)
            
            attr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(20), NSStrokeWidthAttributeName: 2, NSStrokeColorAttributeName: UIColor.redColor()], range: range)
            
            titleView.attributedText = attr
        }else{
        
            titleView.text = "发微博"
        }
        
        titleView.sizeToFit()
        
        
        return titleView
    }()
    
    private lazy var rightButton : UIButton = {
    
        let rightButton = UIButton()
        rightButton.addTarget(self, action: "send", forControlEvents: .TouchUpInside)
        rightButton.setTitle("发送", forState: UIControlState.Normal)
        rightButton.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        rightButton.setBackgroundImage(UIImage(named:"common_button_orange" ), forState: .Normal)
        rightButton.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        //设置不同文字颜色
        rightButton.setTitleColor(UIColor.redColor(),forState: UIControlState.Disabled)
        rightButton.titleLabel?.font = UIFont.systemFontOfSize(13)
        rightButton.frame.size = CGSize(width: 45, height: 28)
        
        return rightButton
    }()
    
}

// MARK: - 通过代理方法把图片写到桌面
extension HTCompostController : UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
//        let  data = UIImagePNGRepresentation(image)
        
        
//        data?.writeToFile("/Users/jonson/Desktop/1.png", atomically: true)
        let img = image.scaleToWidth(600)
        let  data = UIImagePNGRepresentation(img)
        data?.writeToFile("/Users/jonson/Desktop/1.png", atomically: true)
        pictureView.images(img)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
}


extension HTCompostController : UITextViewDelegate{

    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
